package com.cango.framework.base.controller;

import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.cango.qutz.web.common.SessionUtils;
import com.cango.framework.base.entity.SessionUserVo;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.google.gson.GsonBuilder;
import org.apache.logging.log4j.core.util.IOUtils;
import org.springframework.util.StreamUtils;

/**
 * controller的基类<br>
 * 〈功能详细描述〉
 *
 * @author myallways
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本] （可选）
 */
public class BaseController {
    private static final  Log log = LogFactory.getLog(BaseController.class);

    /**
     * <p>
     * Description: ajax输出
     * </p>
     * 
     * @param response
     * @param content
     * @param type
     */
    public void ajax(HttpServletResponse response, String content, String type) {
        try {
            response.setContentType(type + ";charset=utf-8");
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
            response.getWriter().write(content);
            response.getWriter().flush();
        } catch (IOException e) {
            log.error("output message failed!");
        }
    }

    /**
     * <p>
     * Description: ajax输出json
     * </p>
     * 
     * @param response
     * @param obj
     */
    public void ajaxJson(HttpServletResponse response, Object obj) {
        GsonBuilder gb = new GsonBuilder();
        gb.setDateFormat("yyyy-MM-dd");
        String json = gb.create().toJson(obj);
        log.info("json:" + json);
        ajax(response, json, "text/html");
    }

    /**
     * 功能描述: ajax输出json数组<br>
     * 〈功能详细描述〉
     *
     * @param response
     * @param obj
     */
    public void ajaxJsonTree(HttpServletResponse response, Object obj) {
        GsonBuilder gb = new GsonBuilder();
        gb.setDateFormat("yyyy-MM-dd");
        String json = gb.create().toJsonTree(obj).getAsJsonArray().toString();
        log.info("json:" + json);
        ajax(response, json, "text/html");
    }

    /**
     * 功能描述: ajax输出字符窜消息<br>
     * 〈功能详细描述〉
     *
     * @param response
     * @param message
     */
    public void ajaxMessage(HttpServletResponse response, String message) {
        log.info("message:" + message);
        ajax(response, message, "text/html");
    }

    /**
     * <p>
     * Description: 得到当前的session用户对象
     * </p>
     * 
     * @return
     */
    public SessionUserVo getSessionUser() {
        /*RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) ra).getRequest();
        SessionUserVo user = new SessionUserVo();
        // (SessionUserInfo)request.getSession().getAttribute("");
        user.setUserId(1L);
        user.setUserName("admin");*/
        return SessionUtils.getSessionUser();
    }

    /**
     * 功能描述: 文件下载通用<br>
     *
     * @param contentType 请求头信息
     * @param fileInputStream 文件流
     * @param fileName 文件名称
     * @param request 请求
     * @param response 响应
     * @author wzx
     * @date 2015-05-14
     * @throws IOException
     */
    protected void downloadFile(String contentType, InputStream fileInputStream, String fileName, HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.reset();
        response.setContentType(contentType);
        if(request.getHeader("User-Agent").toLowerCase().indexOf("msie") > 0) {
            fileName = URLEncoder.encode(fileName, "UTF-8");
        } else {
            fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");
        }
        response.setHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");
        response.setHeader("Connection", "close");

        StreamUtils.copy(fileInputStream, response.getOutputStream());

        response.flushBuffer();
        fileInputStream.close();
        response.getOutputStream().close();
    }
}
